<template>
  <div class="api-example">
    <h2>API接口调用示例</h2>
    
    <!-- 用户列表示例 -->
    <div class="section">
      <h3>用户管理</h3>
      <div class="buttons">
        <button @click="fetchUsers" :disabled="loading">
          {{ loading ? '加载中...' : '获取用户列表' }}
        </button>
        <button @click="createTestUser" :disabled="loading">
          创建测试用户
        </button>
      </div>
      
      <div v-if="users.length > 0" class="user-list">
        <h4>用户列表：</h4>
        <ul>
          <li v-for="user in users" :key="user.id">
            {{ user.name }} - {{ user.email }}
            <button @click="deleteUser(user.id)" class="delete-btn">删除</button>
          </li>
        </ul>
      </div>
    </div>
    
    <!-- 登录示例 -->
    <div class="section">
      <h3>用户认证</h3>
      <div class="login-form">
        <input 
          v-model="loginForm.username" 
          placeholder="用户名" 
          type="text"
        />
        <input 
          v-model="loginForm.password" 
          placeholder="密码" 
          type="password"
        />
        <button @click="handleLogin" :disabled="loading">
          登录
        </button>
      </div>
      
      <div v-if="currentUser" class="user-info">
        <h4>当前用户：</h4>
        <p>{{ currentUser.name }} ({{ currentUser.email }})</p>
        <button @click="handleLogout">登出</button>
      </div>
    </div>
    
    <!-- 文件上传示例 -->
    <div class="section">
      <h3>文件上传</h3>
      <input 
        type="file" 
        @change="handleFileSelect" 
        ref="fileInput"
      />
      <button @click="uploadFile" :disabled="!selectedFile || loading">
        上传文件
      </button>
    </div>
    
    <!-- 错误信息显示 -->
    <div v-if="error" class="error">
      <h4>错误信息：</h4>
      <p>{{ error }}</p>
      <button @click="clearError">清除错误</button>
    </div>
    
    <!-- 成功信息显示 -->
    <div v-if="success" class="success">
      <h4>操作成功：</h4>
      <p>{{ success }}</p>
      <button @click="clearSuccess">清除消息</button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { userApi, authApi, exampleApi } from '../api/index.js'

export default {
  name: 'ApiExample',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const error = ref('')
    const success = ref('')
    const users = ref([])
    const currentUser = ref(null)
    const selectedFile = ref(null)
    
    // 登录表单
    const loginForm = ref({
      username: '',
      password: ''
    })
    
    // 获取用户列表
    const fetchUsers = async () => {
      try {
        loading.value = true
        error.value = ''
        
        const data = await userApi.getUserList()
        users.value = data
        success.value = '用户列表获取成功'
      } catch (err) {
        error.value = err.message || '获取用户列表失败'
        console.error('获取用户列表失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 创建测试用户
    const createTestUser = async () => {
      try {
        loading.value = true
        error.value = ''
        
        const userData = {
          name: `测试用户${Date.now()}`,
          email: `test${Date.now()}@example.com`,
          password: '123456'
        }
        
        await userApi.createUser(userData)
        success.value = '用户创建成功'
        
        // 重新获取用户列表
        await fetchUsers()
      } catch (err) {
        error.value = err.message || '创建用户失败'
        console.error('创建用户失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 删除用户
    const deleteUser = async (userId) => {
      try {
        loading.value = true
        error.value = ''
        
        await userApi.deleteUser(userId)
        success.value = '用户删除成功'
        
        // 重新获取用户列表
        await fetchUsers()
      } catch (err) {
        error.value = err.message || '删除用户失败'
        console.error('删除用户失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 处理登录
    const handleLogin = async () => {
      try {
        loading.value = true
        error.value = ''
        
        const response = await authApi.login(loginForm.value)
        
        // 保存token
        if (response.token) {
          localStorage.setItem('token', response.token)
        }
        
        // 获取当前用户信息
        const user = await authApi.getCurrentUser()
        currentUser.value = user
        
        success.value = '登录成功'
        
        // 清空表单
        loginForm.value = { username: '', password: '' }
      } catch (err) {
        error.value = err.message || '登录失败'
        console.error('登录失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 处理登出
    const handleLogout = async () => {
      try {
        loading.value = true
        error.value = ''
        
        await authApi.logout()
        
        // 清除本地数据
        localStorage.removeItem('token')
        currentUser.value = null
        
        success.value = '登出成功'
      } catch (err) {
        error.value = err.message || '登出失败'
        console.error('登出失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 处理文件选择
    const handleFileSelect = (event) => {
      selectedFile.value = event.target.files[0]
    }
    
    // 上传文件
    const uploadFile = async () => {
      if (!selectedFile.value) return
      
      try {
        loading.value = true
        error.value = ''
        
        const response = await exampleApi.uploadFile(selectedFile.value)
        success.value = `文件上传成功: ${response.filename}`
        
        // 清空文件选择
        selectedFile.value = null
        if (fileInput.value) {
          fileInput.value.value = ''
        }
      } catch (err) {
        error.value = err.message || '文件上传失败'
        console.error('文件上传失败:', err)
      } finally {
        loading.value = false
      }
    }
    
    // 清除错误信息
    const clearError = () => {
      error.value = ''
    }
    
    // 清除成功信息
    const clearSuccess = () => {
      success.value = ''
    }
    
    // 组件挂载时检查是否已登录
    onMounted(async () => {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const user = await authApi.getCurrentUser()
          currentUser.value = user
        } catch (err) {
          // token可能已过期，清除它
          localStorage.removeItem('token')
          console.error('获取当前用户信息失败:', err)
        }
      }
    })
    
    return {
      loading,
      error,
      success,
      users,
      currentUser,
      selectedFile,
      loginForm,
      fetchUsers,
      createTestUser,
      deleteUser,
      handleLogin,
      handleLogout,
      handleFileSelect,
      uploadFile,
      clearError,
      clearSuccess
    }
  }
}
</script>

<style scoped>
.api-example {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.buttons {
  margin-bottom: 15px;
}

button {
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover:not(:disabled) {
  background-color: #0056b3;
}

button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.delete-btn {
  background-color: #dc3545;
  margin-left: 10px;
  padding: 4px 8px;
  font-size: 12px;
}

.delete-btn:hover:not(:disabled) {
  background-color: #c82333;
}

.user-list {
  margin-top: 15px;
}

.user-list ul {
  list-style-type: none;
  padding: 0;
}

.user-list li {
  padding: 8px;
  margin-bottom: 5px;
  background-color: white;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.login-form {
  margin-bottom: 15px;
}

.login-form input {
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 150px;
}

.user-info {
  padding: 10px;
  background-color: #d4edda;
  border-radius: 4px;
  border: 1px solid #c3e6cb;
}

.error {
  padding: 15px;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  color: #721c24;
  margin-top: 20px;
}

.success {
  padding: 15px;
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
  border-radius: 4px;
  color: #155724;
  margin-top: 20px;
}

h2, h3, h4 {
  color: #333;
}

input[type="file"] {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>